package com.woniu.woniuk16.aop;

import com.woniu.woniuk16.dto.WoniuUserDetails;
import com.woniu.woniuk16.exception.MesException;
import com.woniu.woniuk16.exception.WoniuException;
import com.woniu.woniuk16.model.Result;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
@Aspect
public class MessageManager {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Pointcut(value = "@annotation(com.woniu.woniuk16.aop.Mes)")
    public void mes(){

    }
    @Before("mes()")
    public void getMes(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        Class<?> aClass = args[0].getClass();
        Field message = null;
        try {
            message = aClass.getDeclaredField("message");
        } catch (NoSuchFieldException e) {
            throw new MesException("参数没有验证码");
        }

        message.setAccessible(true);
        String o = null;
        try {
            o = (String) message.get(args[0]);
        } catch (IllegalAccessException e) {
            throw new MesException("定位取得验证码参数");
        }

        WoniuUserDetails woniuUserDetails = (WoniuUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String s = stringRedisTemplate.opsForValue().get("woniu:message:" + woniuUserDetails.getAccountId());
        if (s==null){
            throw new MesException("验证码已失效");
        }else if(o==null){
            throw new MesException("验证码不能为空");
        }
        if (s.equals(o)){
//            stringRedisTemplate.delete("woniu:message:" + woniuUserDetails.getAccountId());
            return;
        }else{
            throw new MesException("验证码错误");
        }

    }
    @AfterReturning(value = "mes()",returning = "result")
    public void after(JoinPoint joinPoint, Boolean result){
        WoniuUserDetails woniuUserDetails = (WoniuUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(result);
        if (result) {
            stringRedisTemplate.delete("woniu:message:" + woniuUserDetails.getAccountId());
        }
    }
}
